<?php
/**
* 分类模型
*/
class ModelsCategoryController extends CommonController
{
    public $categorys;
	
	public $uid;
	
	public $model;
	
	public $models;
	
	public $fields;
	
	public $models_table;
	
	public $models_field_table;
	
	
	
	public function init(){
		parent::init();
	    $this->uid = 'xiong';
		$this->models_table = BackendModels::model()->tableName();
		$this->models_field_table = BackendModels_Field::model()->tableName();
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
     return array( 
        array('auth.filters.AuthFilter'),
            );
        }


    public function actionCreateField($model){
		$model_path = Yii::app()->basePath.'/views/models/model.sql';
		$sql = file_get_contents($model_path);

		$tablename = $model->tablename;
		$sql = str_replace('{{$table}}', '{{'.$tablename.'}}', $sql);
		$sql = str_replace('{{$table_data}}', '{{'.$tablename.'_data}}', $sql);
		$sql = str_replace('$modelid',$model->modelid,$sql);
		return Yii::app()->db->createCommand($sql)->execute();
		exit;
		
		
	}
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate()
	{
		$model=new Models;
        if(isset($_POST['Models']))
		{
			$model->attributes=$_POST['Models'];
			if($model->save()){
				self::updateCache($model->modelid);
				self::actionCreateField($model);
				
                $backurl = $this->createUrl('index');  //跳转到控制器index方法
				$this->jumpPage($backurl);
			}
		}
		$this->renderPartial('models_form',array(
			'model'=>$model,
		));
	}

	/**
	 * 更新数据内容
	 * 模板文件通常为  views/category/_form.php
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionUpdate($modelid)
	{
		$model= $this->loadModel($modelid);
		if(isset($_POST['Models']))
		{
			$model->attributes=$_POST['Models'];
			$model->setting = $model->setting ? json_encode($model->setting) : '';
			if($model->save()){
				$this->updateCache($modelid);
				$backurl = $this->createUrl('index', array('modelid'=>$model->modelid));
				$this->jumpPage($backurl);
			}
		}
        
		$this->models = Yii::app()->filecache->get('backend_models_'.$modelid);
		$this->fields = $this->models['fields'];
		$this->models = $this->models['models'];
		$model->setting = $model->setting ? json_decode($model->setting, true) : array();
		$this->renderPartial('models_form',array(
			'model'=>$model,
		));
	}
	
	


	/**
	 * 删除某一条数据
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
    
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch()
	{
        $ids = isset($_POST['checked_catid']) ? $_POST['checked_catid'] : NULL;
        if ($ids){
            if (isset($_POST['batch_delete'])){
                Category::model()->deleteByPk($ids); 
                //$backurl = $_SERVER['HTTP_REFERER'];
                $backurl = $this->createUrl('index');  //跳转到控制器index方法
				$this->renderPartial('//_return/jump',array(
					'backurl'=>$backurl,
					'type'=> '',
				));
                exit();
            }
        }
	}
    

	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){
		$this->uid = $uid = 'xiong';
		$criteria = new CDbCriteria;
		$sql="SELECT * FROM $this->models_table";
		if (isset($_POST['keyword'])){
			$sql .= " and (title like '%".$_POST['keyword']."%')";
		}
		$sql .= " order by modelid desc";
		$model= Yii::app()->db->createCommand($sql)->queryAll();
		$pages = new CPagination(count($model));               
		$pages->pageSize = 20;
		$pages->applylimit($criteria);
		$model=Yii::app()->db->createCommand($sql." LIMIT :offset,:limit");
		$model->bindValue(':offset', $pages->currentPage*$pages->pageSize);
		$model->bindValue(':limit', $pages->pageSize);
		$rows=$model->queryAll();

		$this->renderPartial('models_index',array(
			'rows'=>$rows,
			'pages'=>$pages,
			'uid'=>$uid
		));
	}

	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionField($modelid){
		$this->uid = $uid = 'xiong';
		$criteria = new CDbCriteria;
		$sql="SELECT * FROM $this->models_field_table where modelid = $modelid";
		
		$sql .= " order by listorder asc,fieldid asc";
		$rows= Yii::app()->db->createCommand($sql)->queryAll();
		

		$this->renderPartial('models_field',array(
			'rows'=>$rows,
			
			'uid'=>$uid,
			'modelid'=>$modelid
		));
	}
	//数据库添加字段
	public function alterField($modelid, $models){
		$sql="SELECT * FROM $this->models_table where modelid = $modelid";
		$model= Yii::app()->db->createCommand($sql)->queryRow();
		$tablename = $models->primarytable ? $model['tablename'] : $model['tablename'].'_data';
		$models->setting = json_decode($models->setting, true);
	    $sql = "alter table `{{{$tablename}}}` add `$models->field` $models->fieldtype";
		$sql .= $models->fieldlength ? "($models->fieldlength)" : "";
		$sql .= $models->setting['defaultvalue'] ? " default '".$models->setting['defaultvalue']."'" : ""; 
		$aa = " not Null";
		Yii::app()->db->createCommand($sql)->execute();
	}
	/**
	 * 新建字段
	 */
	public function actionCreate_field($modelid = '', $fieldid = ''){
		$model = self::loadFieldModel($fieldid);
		if(isset($_POST['Field'])){
			
			$model->attributes=$_POST['Field'];
			$model->setting = json_encode($model->setting);
			$model->param = json_encode($model->param);
			if($model->save()){
				self::updateCache($model->modelid);
				self::alterField($model->modelid, $model);
				$backurl = $this->createUrl('Field', array('modelid'=> $model->modelid));
				$this->jumpPage($backurl);
			}
		}
		
		$formtype = $model->formtype;
		$param = json_decode($model->param, true);

		$this->renderPartial('models_field_form',array(
			'model'=>$model,
			'modelid'=> $modelid
			
		));
	}
	/**
	 * 修改字段
	 * 
	 */
	public function actionUpdate_field($modelid = '', $fieldid){
		$model = self::loadFieldModel($fieldid);
		
		if(isset($_POST['Field'])){
			$model->attributes=$_POST['Field'];
			$model->setting = $model->setting ? json_encode($model->setting) : '';

			$model->param = $model->param ? json_encode($model->param) : '';
			if($model->save()){
				self::updateCache($model->modelid);
				$backurl = $this->createUrl('Field', array('modelid'=> $_POST['Field']['modelid']));
				$this->jumpPage($backurl);
			}
		}
		
		$formtype = $model->formtype;
		
        $model->setting = $model->setting ? json_decode($model->setting, true) : array();
		$model->param = $model->param ? json_decode($model->param, true) : array();   
		$this->renderPartial('models_field_form',array(
			'model'=>$model,
			'modelid'=> $modelid,
			'param' => self::actionFormfield($formtype, $model->param, true)
		));
	}
	
	
	
	
	/**
	* 更新栏目缓存
	*
	*
	*/
	public function updateCache($modelid){
		$sql="SELECT * FROM $this->models_table where modelid = $modelid";
		$data['models'] = Yii::app()->db->createCommand($sql)->queryRow();
        $data['models']['setting'] = $data['models']['setting'] ? json_decode($data['models']['setting'] ,true) : array();
		$data['models']['param'] = $data['models']['param'] ? json_decode($data['models']['param'] ,true) : array();
		$sql="SELECT * FROM $this->models_field_table where modelid = $modelid order by listorder asc, fieldid desc";
		$data['fields'] = Yii::app()->db->createCommand($sql)->queryAll();
		
		$fields = array();
		foreach($data['fields'] as $k=>$v){
		    $v['setting'] = $v['setting'] ? json_decode($v['setting'] ,true) : array();
			$v['param'] = $v['param'] ? json_decode($v['param'] ,true) : array();	
			$fields[$v['fieldid']] = $v;
		}
		$data['fields'] = $fields;
		Yii::app()->filecache->set('backend_models_'.$modelid, $data);
		

		
	}
	
	
	public function actionFormfield($formtype, $param = array(), $return = false){
		$template = "mobo.widgets.$formtype.views._field";
		
		$data['form'] = $this->renderPartial($template,array(
			'formtype'=>$formtype,
			'param' => $param
		), true);
		if ($return){
		     return $data;
		}else{
			echo json_encode($data);
		}
		
	}
	

    public function listorderFields(){
		$fields = array();
		$listorder = isset($this->models['setting']['index']['listorder']) ? $this->models['setting']['index']['listorder'] : array();
		//print_r($listorder);
		//exit;
	    foreach($this->fields as $k=>$v){
			//echo $k.',';
			if(!in_array($k, $listorder)) $fields[$k] = $v;
		}
			
		$fields = array_flip($listorder) + $fields;
		return $fields;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Category the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id = null)
	{
		$model = $id ? BackendModels::model()->findByPk($id) : new BackendModels();
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	public function loadFieldModel($id = null)
	{
		$model = $id ? BackendModels_Field::model()->findByPk($id) : new BackendModels_Field();
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	

	/**
	 * Performs the AJAX validation.
	 * @param Category $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
